package com.example.base_kotlin_xml.view

import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.LogUtils
import com.example.base_kotlin_xml.R
import com.example.base_kotlin_xml.databinding.FragmentHeartbeatMonitorBinding
import com.example.base_model.bean.general.ReceiveData
import com.example.base_model.bean.general.SendData
import com.example.base_model.heart.GlobalHeartbeatManager
import com.example.base_model.other.DeviceCommandManager
import com.example.base_model.other.sendCommandAsFlowWithObject
import com.example.base_model.view.BaseFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @Author: jiangKunKun
 * @CreateDate: 2025/9/30
 * @Description: 心跳监听
 * @SpittingGrooves
 */
@AndroidEntryPoint
class HeartbeatMonitorFragment : BaseFragment<FragmentHeartbeatMonitorBinding>() {
    /**
     * 消息发送和超时监听
     */
    @Inject
    lateinit var deviceCommandManager: DeviceCommandManager
    var deviceKey = 0


    override fun initObservers() {
        // 超时监听
        GlobalHeartbeatManager.networkHeartbeat.startMonitoring(5000) {
            // 处理状态变化
            LogUtils.d("心跳超时！当前状态为： ${GlobalHeartbeatManager.networkHeartbeat.getCurrentState()}")
        }

        // 状态监听
        launchAndCollect {
            GlobalHeartbeatManager.networkHeartbeat.currentState.collectLatest {
                LogUtils.d("当前状态为： $it")
            }
        }
    }

    override fun initClickEvents() {
        // 发送心跳
        mBinding.btnSendHeart.setOnClickListener {
            GlobalHeartbeatManager.networkHeartbeat.sendHeartbeat(true)
        }
        // 获取当前心跳值
        mBinding.btnGetHeart.setOnClickListener {
            LogUtils.d("当前状态为： ${GlobalHeartbeatManager.networkHeartbeat.getCurrentState()}")
        }

        // 发送消息
        mBinding.btnSendMsg.setOnClickListener {
            deviceKey++
            sendMsg()
        }
        // 收到消息
        mBinding.btnReceivedMsg.setOnClickListener {
            val jsonResponse = """{"status":"success","message":"操作完成otherInfo"}"""
            deviceCommandManager.onDeviceResponse(deviceKey.toString(), jsonResponse)
        }
    }

    private fun sendMsg() {
        lifecycleScope.launch {
            deviceCommandManager.sendCommandAsFlowWithObject<SendData, ReceiveData>(
                key = deviceKey.toString(),           // 设备标识符
                commandObject = SendData("test", "data"),  // 发送的数据对象
                timeout = 5000
            ).collectLatest {
                    // 处理结果
                    if (it.success != null) {
                        // 成功接收到响应对象
                        val sendData = it.success?.command  // 类型为 SendData
                        val receiveData = it.success?.response  // 类型为 ReceiveData
                        LogUtils.d("key= ${it.success?.key}, 接收到的数据：${receiveData}","原始数据: $sendData")
                    } else if (it.failure != null) {
                        // 处理失败情况
                        val sendData = it.failure?.command  // 类型为 SendData
                        LogUtils.d("超时！失败消息：key= ${it.failure?.key}, 原始数据: $sendData")
                    }
                }
        }

    }

    override fun initData() {
    }

    override fun onDestroy() {
        super.onDestroy()
        deviceCommandManager.clear()
    }

    override fun attachLayoutRes(): Int = R.layout.fragment_heartbeat_monitor
}